package com.zhou.base.components.feign.cloud.nacoslistener;

import cn.hutool.core.util.StrUtil;
import com.alibaba.cloud.nacos.client.NacosPropertySource;
import com.alibaba.cloud.nacos.parser.NacosDataParserHandler;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.PropertySource;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * @author xianfeng
 * @date 2023/11/30 17:27
 * @description:
 */
@Slf4j
public class SDKListenerTest {

    public static void main(String[] args) throws NacosException {
        String serverAddr = "localhost:8848";
        String dataId = "feign-example11.yaml";
        String group = null;
        Properties properties = new Properties();
        properties.put("serverAddr", serverAddr);
        properties.put("username", "nacos");
        properties.put("password", "nacos");
        properties.put("namespace", "local");
        properties.put("fileExtension", "yaml");
        ConfigService configService = NacosFactory.createConfigService(properties);
        String content = configService.getConfig(dataId, group, 5000);
        System.out.println(content);
        configService.addListener(dataId, group, new Listener() {
            @Override
            public void receiveConfigInfo(String configInfo) {
                if (StrUtil.isNotBlank(configInfo)) {
                    log.info(String.format("Loading nacos data, dataId: '%s', group: '%s'", dataId, group));
                    NacosPropertySource nacosPropertySource;
                    try {
                        List<PropertySource<?>> propertySources = NacosDataParserHandler.getInstance()
                                .parseNacosData(dataId, configInfo,
                                        properties.getProperty("fileExtension"));
                        nacosPropertySource = new NacosPropertySource(propertySources,
                                group, dataId, new Date(), false);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    log.info("spring.application.name={}", nacosPropertySource.getProperty("spring.application.name"));
                    log.info("test.param={}", nacosPropertySource.getProperty("test.param"));
                }
            }

            @Override
            public Executor getExecutor() {
                return null;
            }
        });
        // 测试让主线程不退出，因为订阅配置是守护线程，主线程退出守护线程就会退出。 正式代码中无需下面代码
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
